<?php
/**
 * 答题所有接口方法
 */
namespace app\index\controller;

use think\Controller;
use think\Request;

// use app\index\model\QBank;
// use app\index\model\QUser;
// use app\index\model\QFinish;

class Api extends Controller
{
    private $token;
    // 控制器初始化
	public function _initialize()
    {
        // 在调用其他方法之前，判断token是否在session中，即判断是否登录
        $this->token = empty(Session('userToken')) ? false : Session('userToken');
        // dump($this->token);
        if($this->token)
        {
            // 判断token对不对
            $result = db("q_user")->where("userToken = '$this->token'")->find();
            if(!empty($result) && md5($result['userIDcard']) == $this->token)
            {
                // session 正确
            }
            else
            {
                // return $this->error('请您先进行登录，谢谢',url('/login'));
                // echo "token 错误";
                exit();
            }
        }
        else
        // {echo "请登录";exit();}
        {exit();}
    }

    // 用户每日答题数据
    public function qlists()
    {
        // 已完成的答题
        $finish = db('q_finish')->field('questionNo')->where("userToken = '$this->token'")->select();
        // 当天答题次数
        $answerTimes = db('q_user')->field('answerTimes')->where("userToken = '$this->token'")->find();
        if($answerTimes['answerTimes'] < 15){
            // dump($finish);
            // 排除已答题
            // $datas = db('q_bank')->where("state = 0")->whereNotIn('questionNo',$f)->orderRaw('rand()')->limit(2)->select();
            $datas = db('q_bank')->field("questionNo,questionTitle,questionOption,questionType")->where("state = 0")->select();
            foreach($finish as $v)
            {
                // array_push($f,$v['questionNo']);
                foreach($datas as $key => $value)
                {
                    if($value['questionNo'] == $v['questionNo'])
                    {
                        // unset($datas[$key]);
                        array_splice($datas,$key,1);
                    }
                }
            }
            // dump($datas);
            shuffle($datas);
            // 取题库数据数据
            $q_datas = array_slice($datas,0,15-$answerTimes['answerTimes']);
            // 将选项转为数组
            for($m = 0; $m < count($q_datas); $m++){
                $q_datas[$m]['questionOption'];
                // 处理数据，字符串组变数组
                $q_datas[$m]['questionOption'] = explode("@", $q_datas[$m]['questionOption']);
            }
        }else{
            $q_datas = 0;
        }
        // $q_datas['answerTimes'] = $answerTimes['answerTimes'];
        // $q_datas['score'] = $answerTimes['score'];
        return json(['status'=>0,'data'=>$q_datas]);
    }

    // 判断正误并更新数据
    public function check(Request $req)
    {
        $answerTimes = db('q_user')->field('answerTimes')->where("userToken = '$this->token'")->find();
        if($answerTimes['answerTimes'] < 15){
            $data = $req->param();
            // 判断正误
            $answer = db('q_bank')->field('answer')->where("questionNo = '".$data['questionNo']."'")->find();
            if($answer['answer'] == $data['selectV']){
                // 回答正确，自增一分
                db('q_user')->where("userToken = '$this->token'")->setInc('dayScore');
                db('q_user')->where("userToken = '$this->token'")->setInc('totalScore');
                $message = "正确";
            }else{
                // 回他错误
                $message = "错误";
            }
            // 答题次数自增一次
            db('q_user')->where("userToken = '$this->token'")->setInc('answerTimes');
            // 加入已答题库
            db('q_finish')->insert(['questionNo'=>$data['questionNo'],'userToken' => $this->token,'state'=>0]);
            // return json(['status'=>0,'message'=>$message,'answerTimes'=>$data['answerTimes']+1]);
            return json(['status'=>0,'message'=>$message,'data'=>$data]);
        }else{
            return json(['status'=>1]);
        }
    }

    // 查询分数，判断是否可以领奖,每日的头盔奖励
    public function checkreward()
    {
        $score = db('q_user')->field('dayScore')->where("userToken = '$this->token'")->find();
        if($score['dayScore'] >= 10 && $score['dayScore'] <= 15){
            // 判断是否为前100名
            $countReward = db('q_reward')->where("reward = 1 and FROM_UNIXTIME(time, '%Y%m%d') = ".date('Ymd'))->count();
            if($countReward < 100){
                // 即当天可以领取一个头盔,reward = 1
                $res = db('q_reward')->where(['userToken'=>$this->token,'reward'=>1])->find();
                if($res){
                    $message = "限领一顶头盔，请于3月26日前往湖南人民广播电台领取";
                }else{
                    db('q_reward')->insert(['userToken'=>$this->token,'reward'=>1,'time'=>time()]);
                    // 头盔数存量减一，表示发出加一
                    db('q_prize')->where('prizeCode = 1')->setInc('prizeOut');
                    $message = "奖励头盔一顶，请于3月26日前往湖南人民广播电台领取";
                }
            }else{
                $message = "今日100顶头盔已领完";
            }
            return json(['status'=>0,'message'=>$message]);
        }else{
            return json(['status'=>0,'message'=>'不满足奖励条件']);
        }
    }

    public function checkbaoxian()
    {
        $score = db('q_user')->field('totalScore')->where("userToken = '$this->token'")->find();
        if($score >= 40 && $score < 80){
            // 奖励价值100元的保险
            db('q_reward')->insert(['userToken'=>$this->token,'reward'=>2,'time'=>time()]);
            // 奖励价值100元的保险,发出数加一
            db('q_prize')->where('prizeCode = 2')->setInc('prizeOut');
            $message = "奖励价值100元的一年期保险一份";
        }else if($score >= 80){
            $res = db('q_reward')->where(['userToken'=>$this->token,'reward'=>2])->find();
            if($res){
                // 用户已有100元1年期保险,升级为300元3年期的
                db('q_reward')->where(['userToken'=>$this->token,'reward'=>2])->update(['reward'=>3,'time'=>time()]);
                // 100元一年期的奖励，发出数减一
                db('q_prize')->where('prizeCode = 2')->setDec('prizeOut');
                // 300元的保险奖励,发出数加一
                db('q_prize')->where('prizeCode = 3')->setInc('prizeOut');
                $message = "奖励价值300元的三年期保险一份";
            }else{
                // 用户没有领保险奖励
                db('q_reward')->insert(['userToken'=>$this->token,'reward'=>3,'time'=>time()]);
                // 100元一年期的奖励，发出数减一
                // db('q_prize')->where('prizeCode = 2')->setDec('prizeOut');
                // 200元两年期的奖励，发出数加一
                db('q_prize')->where('prizeCode = 3')->setInc('prizeOut');
                $message = "奖励升级为价值300元的三年期保险一份";
            }
        }
        return json(['status'=>0,'message'=>$message]);
    }

    // 查询当天剩余答题次数
    public function checkchange()
    {
        $answerTimes = db('q_user')->field("answerTimes")->where("userToken = '$this->token'")->find();
        if($answerTimes['answerTimes'] < 15 ){
            $status = 0;
        }else{
            $status = 1;
        }
        return json(["status"=>$status]);
    }

    public function score()
    {
        $score = db('q_user')->field("dayScore,totalScore")->where("userToken = '$this->token'")->find();
        return json(['status'=>0,'data'=>$score]);
    }
}
